#include "bsp_epit.h"
#include "bsp_init.h"
#include "bsp_led.h"
#include "bsp_beep.h"
#include "bsp_gpio.h"


void epit1_init(unsigned int prescaler , unsigned int epit_lr_data){

    /*为防止赋值出错，先将epit_cr清0*/
    EPIT1->CR = 0;

    /*配置EPIT_CR*/
    EPIT1->CR |= (1<<1) |  (1<<3) | (prescaler << 4) | (1<<24);

    /*配置EPIT_LR*/
    EPIT1->LR = epit_lr_data;

    /*配置EPIT_CMPR*/
    EPIT1->CMPR = 0;

    /*打开epit计时器，该计时器未打开中断*/
    //EPIT1->CR |= (1<<0);

    
}


void epit1_irqhandler (unsigned int gicciar, void *param){
    
    static unsigned char state = 0;
    /*判断是否产生了比较事件*/
  //  if(EPIT1->SR == 1){
  //      state =! state;
  //      if(state == 0){
  //          led_close();
  //      }
  //      else led_open();

  //      EPIT1->SR |= (1<<0);
  //  }
}


void epit2_init(unsigned int prescaler , unsigned int epit_lr_data){

    /*为防止赋值出错，先将epit_cr清0*/
    EPIT2->CR = 0;

    /*配置EPIT_CR*/
    EPIT2->CR |= (1<<1) | (1<<2) | (1<<3) | (prescaler << 4) | (1<<24);

    /*配置EPIT_LR*/
    EPIT2->LR = epit_lr_data;

    /*配置EPIT_CMPR*/
    EPIT2->CMPR = 0;

    /*使能epit中断号*/
    GIC_EnableIRQ(EPIT2_IRQn);
    
    /*注册中断函数*/
    system_register_irqhandler(EPIT2_IRQn , epit2_irqhandler, NULL);

    
}

void epit2_irqhandler(unsigned int gicciar, void *param){

    static unsigned char beep_state = 0;
    if(EPIT2->SR == 1){
        EPIT2->CR &= ~(1<<0);
        if( gpio_read_pin(GPIO1 , 18) == 0 ){
            beep_state = !beep_state;
            if(beep_state){
                beep_open();
            }
            else{
                beep_close();
            }
        }
    }
    
    EPIT2->SR |= (1<<0);
    
}